<template>
  <div ref="target" class="w-full " @pointerdown="isShow=true">
    <div v-if="isLogin">
      <n-button style="height: 100px" @click="handleLogin" block quaternary> 看完啦，
        <div class="text-blue-500">登录</div>
        分享一下感受吧～
      </n-button>
    </div>
    <div v-else class="space-y-3">
      <n-input v-model:value="content" type="textarea"
               class="rounded-lg"></n-input>
      <div class="flex justify-end">
        <n-button v-if="isShow" type="success" class="bg-green-600" @click.stop="handleComment">发表</n-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">


import {ref} from "vue";
import { useUserStore} from "@/store/module/user";
import {useAppStore} from "@/store/module/app";
import {storeToRefs} from "pinia";
import api from "@/api";
import {onClickOutside} from '@vueuse/core'

const userStore = useUserStore()
const {userInfo,isLogin} = storeToRefs(userStore)
const appStore = useAppStore()
const {authModalShow} = storeToRefs(appStore)
import {useDebounceFn} from '@vueuse/core'
const target = ref(null)
onClickOutside(target, () => isShow.value = false)
const props = defineProps({
  targetId: {
    type: String,
    required: true
  }
})
const emits = defineEmits(['commentSuccess'])

const content = ref('')
const isShow = ref(false)

const handleLogin = () => {
  authModalShow.value = true
}

const handleComment = useDebounceFn(() => {
  api.comment.createPostComment({
    targetId: props.targetId,
    fromId: userInfo.value.id,
    fromUsername: userInfo.value.username,
    fromAvatar: userInfo.value.avatar,
    content: content.value
  }).then(res => {
    if (res.data.code === 0) {
      emits('commentSuccess',{
        targetId: props.targetId,
        fromId: userInfo.value.id,
        fromUsername: userInfo.value.username,
        fromAvatar: userInfo.value.avatar,
        content: content.value,
        replyList: []
      })
      content.value = ''
      window.$message.success('评论成功')
    }
  })
}, 200)


</script>

<style scoped>

</style>